//
//  MyForSaleCardsViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/28.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyForSaleCardsViewController.h"
#import "MyForSaleCardTableViewCell.h"
#import "UseForMoneyDetailViewController.h"
static NSString * cellIndentifier = @"MyForSaleCardTableViewCell";

@interface MyForSaleCardsViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UILabel *headTitle;
@property (strong, nonatomic) IBOutlet UIView *selectedBackView;
@property (strong, nonatomic) IBOutlet UIView *selectedView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,assign)NSInteger selectedIndex;

@property(nonatomic,strong)NSMutableArray * forSaleArray;
@end

@implementation MyForSaleCardsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _selectedIndex = 100;
    _pageNO = 1;
    _forSaleArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.selectedBackView];
    
    if (_type == 1 ) {
        _headTitle.text = @"我的优惠券";
    }else{
     _headTitle.text = @"我的代金券";
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];

}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getForSaleList];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.forSaleArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getForSaleList];
        });
    }
    
}


#pragma mark  ＝＝＝＝获取优惠劵  代金券列表
- (void)getForSaleList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    if (_selectedIndex == 100) {
        [dic setObject:@"0" forKey:@"isOk"];
      
    }else if(_selectedIndex == 101){
        [dic setObject:@"1" forKey:@"isOk"];
    }
    if (_type == 1) {
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryCoponByStateId withHttpType:@"POST" withTag:SX_SX_queryCoponByStateId];
    }else{
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryVoucher withHttpType:@"POST" withTag:SX_SX_queryVoucher];
    }
    
    
    
}

- (IBAction)changeCardType:(UIButton *)sender {
    sender.selected = YES;
    if (sender.tag == _selectedIndex) {
        return;
    }
    UIButton * button = [self.view viewWithTag:_selectedIndex];
    button.selected = NO;
    _selectedIndex = sender.tag;
    [UIView animateWithDuration:0.2 animations:^{
        _selectedView.frame = flexibleFrame(CGRectMake(160*(sender.tag-100), 41, 160, 1), YES);
    }];
    
//    [self getForSaleList];
    [self.tableView.header beginRefreshing];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120*VerticalRatio();
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _forSaleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyForSaleCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell= [[MyForSaleCardTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    NSDictionary * dic= _forSaleArray[indexPath.row];
    
    NSString * string = @"";
    if (_type==1) {
        string = @"优惠券";
        NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@%@",dic[@"mscoDecreaseAmount"],string]];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28*VerticalTexeRatio()] range:NSMakeRange(1, [NSString stringWithFormat:@"%@",dic[@"mscoDecreaseAmount"]].length)];
        cell.forSaleMoney.attributedText = str;
        
        
        cell.storeName.text =[NSString stringWithFormat:@"%@", dic[@"StoreName"]];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        if(![dic[@"mscoInvalidateDate"] isEqual:[NSNull null]]){
            NSDate *confromTimesp1 = [NSDate dateWithTimeIntervalSince1970:[dic[@"mscoInvalidateDate"] integerValue]/1000];
            [formatter setDateFormat:@"yyyy.MM.dd"];
            NSString *endTime = [formatter stringFromDate:confromTimesp1];
            cell.timeLabel.text = [NSString stringWithFormat:@"有效期至%@",endTime];
        }
        if (_selectedIndex == 100) {
            [cell.timeOutButton setImage:[UIImage imageNamed:@"myForSaleCard6"] forState:UIControlStateNormal];
        }else if (_selectedIndex == 101){
            [cell.timeOutButton setImage:[UIImage imageNamed:@"myForSaleCard5"] forState:UIControlStateNormal];
        }
    }else{
    string = @"代金券";
        NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@%@",dic[@"mgpiOrginalAmount"],string]];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28*VerticalTexeRatio()] range:NSMakeRange(1, [NSString stringWithFormat:@"%@",dic[@"mgpiOrginalAmount"]].length)];
        cell.forSaleMoney.attributedText = str;
        
        
        cell.storeName.text =[NSString stringWithFormat:@"%@", dic[@"storeName"]];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        if(![dic[@"mgtiValidEndDate"] isEqual:[NSNull null]]){
            NSDate *confromTimesp1 = [NSDate dateWithTimeIntervalSince1970:[dic[@"mgtiValidEndDate"] integerValue]/1000];
            [formatter setDateFormat:@"yyyy.MM.dd"];
            NSString *endTime = [formatter stringFromDate:confromTimesp1];
            cell.timeLabel.text = [NSString stringWithFormat:@"有效期至%@",endTime];
        }
        if (_selectedIndex == 100) {
            [cell.timeOutButton setImage:[UIImage imageNamed:@"myForSaleCard6"] forState:UIControlStateNormal];
        }else if (_selectedIndex == 101){
            [cell.timeOutButton setImage:[UIImage imageNamed:@"myForSaleCard5"] forState:UIControlStateNormal];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_type == 2 ){
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
        UseForMoneyDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"UseForMoneyDetail"];
        page.detailId = _forSaleArray[indexPath.row][@"mgprId"];
        [self.navigationController   pushViewController:page animated:YES];
    }
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag == SX_SX_queryCoponByStateId){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!_tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        _tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.forSaleArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.forSaleArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
        }
    }else if (tag == SX_SX_queryVoucher){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!_tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        _tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.forSaleArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.forSaleArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
